package com.test.daily.leetcode.y2022.m01.day0106;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * SimplifyPath
 *
 * @author Tom on 2022/1/6
 */
public class Code01_SimplifyPath {
    public String simplifyPath(String path){
        String[] names = path.split("/");
        Deque<String> stack = new ArrayDeque<String>();
        for(String name: names){
            if("..".equals(name)){
                if(!stack.isEmpty()){
                    stack.pollLast();
                }
            } else if(name.length() > 0 && !".".equals(name)){
                stack.offerLast(name);
            }
        }
        StringBuffer ans = new StringBuffer();
        if(stack.isEmpty()){
            ans.append('/');
        } else {
            while(!stack.isEmpty()){
                ans.append('/');
                ans.append(stack.pollFirst());
            }
        }
        return ans.toString();
    }
}
